package com.ruoyi.web.controller.student;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.domain.FileEntity;
import com.ruoyi.service.FileEntityService;
import com.ruoyi.web.controller.common.CommonController;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;

@RestController
@RequestMapping("/system/file")
public class FileEntityController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private FileEntityService fileEntityService;
    @Log(title = "保存文件数据库标志", businessType = BusinessType.INSERT)
    @PostMapping("/saveFile")
    public R add(@RequestBody List<FileEntity> fileEntityList)
    {
        return fileEntityService.addFileEntity(fileEntityList);
    }


    @GetMapping("/getFileList")
    public R getlist(@Param("taskId") String taskId)
    {   Long userid = getUserId();
        return fileEntityService.getFileList(taskId,userid);

    }


    @GetMapping("/getFileListByRowId")
    public R getFileListByRowId(@Param("rowId") String rowId)
    {

        return fileEntityService.getFileListByRowId(rowId);

    }


//    @GetMapping("/download")
//    public void fileDownload(String fileName, String filePath , HttpServletResponse response, HttpServletRequest request)
//    {
//        try
//        {
//            if (!FileUtils.checkAllowDownload(fileName))
//            {
//                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//            }
//            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            FileUtils.setAttachmentResponseHeader(response, realFileName);
//            FileUtils.writeBytes(filePath, response.getOutputStream());
//        }
//        catch (Exception e)
//        {
//            log.error("下载文件失败", e);
//        }
//    }



//    @GetMapping("/download")
//    public ResponseEntity<Void> fileDownload(
//            @RequestParam String fileName,
//            @RequestParam String filePath,
//            HttpServletResponse response) {
//
//        try {
//            System.out.println("走这里了");
//            // 1. 检查文件名合法性
//            if (!FileUtils.checkAllowDownload(fileName)) {
//                return ResponseEntity.badRequest()
//                        .header("X-Error-Message", "文件名非法")
//                        .build();
//            }
//
//            // 2. 检查文件是否存在
//            File file = new File(filePath);
//            if (!file.exists() || !file.isFile()) {
//                return ResponseEntity.notFound()
//                        .header("X-Error-Message", "文件不存在")
//                        .build();
//            }
//
//            // 3. 处理文件名（更安全的逻辑）
//            String realFileName;
//            try {
//                realFileName = System.currentTimeMillis() + "_" +
//                        fileName.substring(fileName.lastIndexOf("_") + 1);
//            } catch (StringIndexOutOfBoundsException e) {
//                realFileName = System.currentTimeMillis() + "_" + fileName; // 默认处理
//            }
//
//            // 4. 设置响应头
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
//                    "attachment; filename=\"" + URLEncoder.encode(realFileName, String.valueOf(StandardCharsets.UTF_8)) + "\"");
//
//            // 5. 写入文件流（确保资源关闭）
//            try (InputStream is = new FileInputStream(file);
//                 OutputStream os = response.getOutputStream()) {
//                IOUtils.copy(is, os);
//                System.out.println(os);
//            }
//            System.out.println("下载成功了");
//            return ResponseEntity.ok().build();
//        } catch (Exception e) {
//            log.error("下载文件失败", e);
//            return ResponseEntity.internalServerError()
//                    .header("X-Error-Message", "服务器内部错误")
//                    .build();
//        }
//    }


    @PostMapping("/fileDownload")
    public ResponseEntity<InputStreamResource> fileDownload(@RequestBody Map<String, String> params) throws IOException {
        String filePath = params.get("filePath");
        String fileName = params.get("fileName");
        //System.out.println("filePath=============="+filePath);
        System.out.println("fileName=============="+fileName);
        //filePath = "D:\\22.rar";
        FileInputStream fileInputStream = new FileInputStream(filePath);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+fileName)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(fileInputStream));
    }





}
